// 1. 导入所需的包
import Vue from 'vue'
import Vuex from 'vuex'
import VuexPersistence from 'vuex-persist' //持久化存储

// ------------------------ 导入小模块 --------------------------
import medicine from './modules/medicine'
import doctor from './modules/doctor'
import nurse from './modules/nurse'
import patient from './modules/patient'
import sickroom from './modules/sickroom'
import board from './modules/board'
import expense from './modules/expense'
import router from '@/router'

// 2. 将Vuex注册为Vue的插件
Vue.use(Vuex)

const vueLocal = new VuexPersistence({
  storage: window.localStorage
})

// 3. 创建 store 实例对象
const store = new Vuex.Store({
  /* 这里配置Vuex */
  strict: true, // 开启严格模式，防止在组件中直接修改state数据
  // 注册为模块
  modules: {
    // 模块名: 导入的变量名
    medicine,
    doctor,
    nurse,
    patient,
    sickroom,
    board,
    expense,
  },
  plugins: [vueLocal.plugin]
})

// 4. 全局前置导航守卫
router.beforeEach((to, from, next) => {
  //to.path 即将要访问的地址
  if (to.path === '/')
    next(); //访问的为登陆界面时，无条件放行
  else {
    const user = localStorage.getItem('user')
    console.log(user);
    if (user)
      next();
    else
      next('/')  // 没有登录，强制跳转到登录页
  }
})

// 5. 导出 store 对象
export default store